package cn.com.ctcloud.saas.core.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * Title: Kernel Library
 * <p>
 * Description: 有关Web开发中使用的工具类
 * <p>
 * Copyright: Copyright (c) 2010 - 2011
 * <p>
 * Company: Liaoning Open Data Communication Co.,Ltd.
 * 
 * @author Charles (Li Hui)
 * @version 1.0.2
 */
public class WebUtil {

	/**
	 * 判断是否url地址
	 * 
	 * @author Charles (Li Hui)
	 * @date 2011-10-19 上午11:00:04
	 * @param url
	 *            地址
	 * @return true/false
	 */
	public static boolean isUrl(final String url) {
		boolean isOk = false;
		if (StringUtils.isNotEmpty(url)) {
			final Pattern pattern = Pattern.compile("(http://|https://){1}[\\w\\.\\-/:]+");
			final Matcher matcher = pattern.matcher(url);
			if (matcher.find()) {
				isOk = true;
			}
		}
		return isOk;
	}

	/**
	 * 判断是否是IP地址
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isIPAdress(final String str) {
		final Pattern pattern = Pattern.compile(
				"^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 获取用户真实Ip
	 * 
	 * @author Charles (Li Hui)
	 * @date 2011-8-29 上午11:32:12
	 * @param request
	 *            HttpServletRequest
	 * @return Ip地址
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
				//根据网卡取本机配置的IP  
				InetAddress inet = null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress = inet.getHostAddress();
			}
		}
		//对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割  
		if (ipAddress != null && ipAddress.length() > 15) { //"***.***.***.***".length() = 15  
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

	/**
	 * 获取当前操作系统名称. return 操作系统名称 例如:windows xp,linux 等.
	 */
	public static String getOSName() {
		return System.getProperty("os.name").toLowerCase();
	}

	/**
	 * 批量执行DOC命令
	 * 
	 * @author Charles (Li Hui)
	 * @param cmd
	 *            命令集合
	 * @return 执行后的返回结果
	 */
	public static String callCmd(final String[] cmd) {
		String result = "";
		String line = "";
		try {
			final Process proc = Runtime.getRuntime().exec(cmd);
			final InputStreamReader is = new InputStreamReader(proc.getInputStream());
			final BufferedReader br = new BufferedReader(is);
			while ((line = br.readLine()) != null) {
				result += line;
			}
		} catch (final Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 获取URL的模型
	 * <p>
	 * 例如：http://localhost:8080/disk
	 * <p>
	 * 输出：localhost:8080
	 * 
	 * @param uri
	 *            URL地址
	 * @return 模型
	 */
	public static String getModule(final String uri) {
		if (uri == null) {
			return "";
		}
		final String[] uriArr = uri.split("/");
		if (uriArr != null && uriArr.length > 2) {
			return uriArr[2];
		} else {
			return "";
		}
	}

	/**
	 * 获取URL的HOST
	 * <p>
	 * 例如：http://localhost:8080/disk
	 * <p>
	 * 输出：localhost
	 * 
	 * @param url
	 *            URL地址
	 * @return 模型
	 */
	public static String getHost(final String url) {
		if (url == null) {
			return "";
		}
		if (url.indexOf("http://") == 0) {
			return StringUtils.substringBetween(url, "http://", ":");
		} else if (url.indexOf("https://") == 0) {
			return StringUtils.substringBetween(url, "https://", ":");
		}
		return StringUtils.substringBefore(url, ":");
	}

	/**
	 * 获取网站URL地址，最有必须加/
	 * <p>
	 * 例如：http://localhost:8080/test/
	 * 
	 * @param request
	 *            HttpServletRequest
	 * @return 地址
	 */
	public static String getWebUrl(final HttpServletRequest request) {
		if (request == null) {
			return "";
		}
		return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
				+ request.getContextPath() + "/";
	}

	/**
	 * 获取某一个url的ip
	 * <p>
	 * 例如：http://www.baidu.com:80
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：www.baidu.com:80
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：www.baidu.com
	 * <p>
	 * 返回：192.168.100.122
	 * <p>
	 * 例如：192.168.100.122
	 * <p>
	 * 返回：192.168.100.122
	 * 
	 * @param url
	 *            URL地址
	 * @return IP
	 */
	public static String getIpFromUrl(final String url) {
		if (StringUtils.isEmpty(url)) {
			return "";
		}
		try {
			final InetAddress iAddress = InetAddress.getByName(WebUtil.getHost(url));
			return iAddress.getHostAddress();
		} catch (final UnknownHostException e) {
			Log.error(e.getMessage());
			return "";
		}
	}

	/**
	 * 测试
	 * 
	 * @author Charles (Li Hui)
	 * @date 2013-12-21 上午9:15:01
	 * @param args
	 *            参数
	 */
	public static void main(final String[] args) {
		System.out.println(WebUtil.getModule("http://localhost:8080/disk/download.xhtml"));
		System.out.println(WebUtil.getHost("http://localhost:8080/disk/download.xhtml"));
		System.out.println(WebUtil.getIpFromUrl("http://www.baidu.com:80"));
		System.out.println(WebUtil.isIPAdress("10.0.2.54"));
	}

}
